<template>
  <div id="app">
    <h1>商品列表</h1>
    <button @click="sortByPriceAscending">按价格升序排序</button>
    <button @click="sortByPriceDescending">按价格降序排序</button>
    <ul>
      <li v-for="item in sortedItems" :key="item.name"> <img style="width: 30px; height: 30px;" :src="item.img"
          alt="">
        <div>{{ item.name }} </div>
        <div>{{ item.price }} </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue';


const items = ref([
  { id: 1, name: '苹果', price: 5, img: "/public/free01.png" },
  { id: 2, name: '香蕉', price: 2, img: "/public/free02.png" },
  { id: 3, name: '橙子', price: 4, img: "/public/free03.png" },
  { id: 4, name: '葡萄', price: 6, img: "/public/free04.png" },
]);
const sortedItems = ref([...items.value]);

const sortByPriceAscending = () => {
  console.log('升序', sortedItems.value);
  sortedItems.value = [...items.value].sort((a, b) => a.price - b.price);
};

const sortByPriceDescending = () => {
  console.log('降序', sortedItems);

  sortedItems.value = [...items.value].sort((a, b) => b.price - a.price);



};
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}

button {
  margin: 5px;
}
</style>
